<?php

//connect to the admin database 
if ($db = sqlite_open('AdminDB', 0666, $sqliteerror)) { 
    $dbcreate = new PDO('sqlite:AdminDb_PDO.sqlite');
    $dbcreate->exec("CREATE TABLE IF NOT EXISTS AdminDB(_id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT, groupID INTEGER)"); 
} else {
    die($sqliteerror);

if(isset($_COOKIE["groupID"]))
{
   $groupID = $_COOKIE["groupID"];
  // $username = $_COOKIE["username"];
  // $password = $_COOKIE["password"];

   //$cookie_query = "SELECT * FROM AdminDB WHERE username='$username' AND password='$password' AND groupID='$groupID'";
   $cookie_query = "SELECT * FROM AdminDB WHERE groupID='$groupID'";
   $cookie_result = sqlite_query($db,$cookie_query)

  while($cookie_check = sqlite_fetch_array($cookie_result,SQLITE_ASSOC))
  {
     if($groupID != $cookie_check["groupID"])
     {
	//redirect to login page
	header("Location:web.cs.miami.edu/home/jdla531/Sources/login.html");
     }

     else
	header("Location:web.cs.miami.edu/home/jdla531/admin.html");  //fetch admin page
  }
}
else
{
   if(!$_POST["usrnm"] || !$_POST["pwd"])
   {
     //Provide a value for username and password
     die('Provide a value for username and/or password fields');
   }

   $sql_query = "SELECT * FROM AdminDB WHERE username='$_POST["usrnm"]' AND password='$_POST["pwd"]'";

   $result = sqlite_query($db,$sql_query);
   if($check_result = sqlite_fetch_array($result,SQLITE_ASSOC))
   {
    //add cookie stuff here
    $expire_tm = time()+3600;
    if($_GET["pwd"] != $check_result["password"] && $_GET["usrnm"]!= $check_result["username"])
      die("Username or password do not match");
    setcookie("groupID",$check_result["groupID"],$expire_tm,'/');
   // setcookie("username",$_POST["usrnm"],$expire_tm,'/');
   // setcookie("password",md5($_POST["pwd"]),$expire_tm,'/');
 
    echo "<strong>Log in successful</strong><br/><br/>"; 
    echo "Welcome ".$_POST["usrnm"];
    //redirect to admin page
    header("Location:web.cs.miami.edu/home/jdla531/Sources/admin.html");
   }
   else
   {
    //login unsuccessful
    die("Wrong Username or password");
   }
}

?>
